// stores/permission.js
import { defineStore } from 'pinia'
import { authRoutes } from '@/router/routes'

export const usePermissionStore = defineStore('permission', {
  state: () => ({
    routes: [],
    hasGenerated: localStorage.getItem('routeGenerated') === 'true'
  }),
  
  actions: {
    async generateRoutes(roles) {
      // 清空旧路由状态
      this.routes = [];
      this.hasGenerated = false;
      
      // 递归过滤逻辑（保留子路由）
      const filterRoutes = (routes) => {
        return routes.filter(route => {
          // 验证主路由权限
          const requiredRoles = route.meta?.roles || [];
          const hasPermission = requiredRoles.length === 0 || 
                 requiredRoles.some(r => userRoles.includes(r));
          
          // 处理嵌套路由（关键修复）
          if (hasPermission && route.children) {
            route.children = filterRoutes(route.children);
          }
          
          console.log(`[路由过滤] ${route.path}: ${hasPermission ? '通过' : '拒绝'}`);
          return hasPermission;
        });
      };

      this.routes = filterRoutes(authRoutes);
      console.log('[权限路由] 过滤结果:', this.routes);
    }
    
    setHasGenerated(status) {
      this.hasGenerated = status;
      localStorage.setItem('routeGenerated', Date.now());
    }
  }
});
